import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  HttpCode,
  HttpException,
  UseGuards,
  Query,
} from '@nestjs/common';
import { RateLimit, } from 'nestjs-fastify-rate-limiter'
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ApiBearerAuth, ApiBody, ApiHeader, ApiOkResponse, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger';
import { PageDto } from './dto/page.dto';
import { PageVto } from '../../common/Vto/page.vto';
import { UserEntity } from './entities/user.entity';
import { CommonService } from 'src/common/common.service';
import dayjs from 'dayjs';
import { ChatApiService } from '../chat-api/chat-api.service';

@Controller('user')
//eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6OCwiaWF0IjoxNjg4OTcxMzMwLCJleHAiOjE2ODkwMDAxMzB9.PsydAhPy2sbKC7tNbtq-EPJc1r08sRvuKhyyAIlLUJY
// @UseGuards(TokenAuth)
@ApiTags('User')
export class UserController {
  constructor(private readonly userService: UserService, private jwt: CommonService,private common :CommonService,private chatApiService :ChatApiService) {}
   
  @Post('/register')
  @HttpCode(200)
  async register(@Body() user: CreateUserDto) {
    //判断用户是否存在
    let result = await this.userService.isHave(user.username);
    if (result > 0) {
      throw new HttpException({ code: 0, message: '用户已存在' }, 200);
    }
    let UserData = await this.userService.createUser(user)
    if(UserData.id >0){
      await this.chatApiService.addGroup(UserData.id)
      return {
        code: '1',
        message: '注册成功',
      };
    }else{
      throw new HttpException({code:0,message:"注册失败"},200)
    }
  }
  
  @Post('/login')
  @HttpCode(200)
  @RateLimit({
    points: 3,
    duration: 60,
    errorMessage: 'You have reached the limit. You have to wait 60 seconds before trying again'
})
  async userLogin(@Body() user: CreateUserDto) {
    if ((await this.userService.isHave(user.username)) == 0) {
      throw new HttpException({ code: 0, message: '用户不存在' }, 200);
    }

    let userInfo = await this.userService.findOne(user.username);
    if (user.password == userInfo.password) {
      let token = await this.jwt.loginSign(userInfo.id)
      return {
        code: 1,
        message: '登录成功',
        token
      };
    } else {
      throw new HttpException({ code: 0, message: '密码错误' }, 200);
    }
  }
  /**
   * @author nie
   * @description 获取用户列表
   */
  @Get('/list')
  @ApiQuery({ name: 'pageSize', required: false })
  @ApiQuery({ name: 'pageNum', required: false })
  // @ApiOkResponse({type:PageVto})
  async getUserList(@Query() page: PageDto){
    let result = await this.userService.getAllUser(page);
    return result
    let data = new PageVto<UserEntity>();
    data.pageNum = page.pageNum;
    data.pageSize = page.pageSize;
    data.list = result[0];
    data.total = result[1];
    return data;
  }
}
